package com.way.demo.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.way.demo.bo.ReqTestBo;
import com.way.demo.bo.Student;
import com.way.demo.comm.R;
import com.way.demo.comm.exception.Assert;
import com.way.demo.comm.result.ApiCode;
import com.way.demo.comm.result.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lipingwei
 * @create 2021-01-21 20:51
 */

@RestController
@RequestMapping("/test")
@Slf4j
@Validated
public class TestController {

    @PostMapping("/queryid")
    public R<ReqTestBo> queryTest(@RequestBody @Valid ReqTestBo reqTestBo) throws Exception {


        ThreadLocal<String> threadLocal = ThreadUtil.createThreadLocal(false);
        String s = threadLocal.get();
        log.info("入参为：{}", reqTestBo);
        reqTestBo.setName("zhangsan").setAddr("bj");

        String str ="hello test";
//        if(true){
//            throw new BusinessException("444","bubuubuu");
//        }
        return R.success(reqTestBo);
    }

    @GetMapping ("/queryid2")
    public R<String> queryTest2(@RequestParam @Valid String name,String age) throws Exception {
          log.info("name 为： {}",name);
           return R.success(name);
    }
    @RequestMapping("/io")
    public void testIo() throws IOException {

        InputStream streamSafe = ResourceUtil.getStreamSafe("files/a.png");
        String absolutePath = new ClassPathResource("files/").getAbsolutePath();
        String s = String.valueOf(System.currentTimeMillis());
        BufferedOutputStream outputStream = FileUtil.getOutputStream(absolutePath.concat(s).concat(".png"));
        IoUtil.copy(streamSafe,outputStream);


        //    long copySize = IoUtil.copy(inputStream, outputStream, IoUtil.DEFAULT_BUFFER_SIZE);

    }

    /**
     * test API
     */
    @PostMapping("/test01")
    public ApiResult<Void> test(){
        return ApiResult.ok();
    }

    @PostMapping("/test02")
    public ApiResult<ReqTestBo> test2(@RequestBody @Valid ReqTestBo reqTestBo){
        reqTestBo.setName("zhangsan").setAddr("bj");
        return ApiResult.ok("result",reqTestBo);
    }
    @GetMapping("/test03")
    public ApiResult<ReqTestBo> test3(@Valid ReqTestBo reqTestBo){
        reqTestBo.setName("zhangsan").setAddr("bj");
        List<String> strings = Arrays.asList("1", "2", "3");
        return ApiResult.ok(strings);
    }

    /**
     * 对嵌套参数的校验
     * 例如：BO类中包含另一个对象Student,需要在对象参数上添加 @Valid 才会生效。（@Validated不生效,不能添加在属性上）
     * @param reqTestBo
     * @return
     */
    @PostMapping ("/test04")
    public ApiResult<ReqTestBo> test4(@Valid  @RequestBody ReqTestBo reqTestBo){
        reqTestBo.setName("zhangsan").setAddr("bj");
        reqTestBo.setName("zhangsan").setAddr("bj");
        List<String> strings = Arrays.asList("1", "2", "3");

        return ApiResult.ok(strings);
    }

    /**
     *  验证 get 请求时，使用@RequestParam 参数校验生效的情况，会被ConstraintViolationException异常拦截
     * @param name
     * @return
     */
    @GetMapping  ("/test05")
    public ApiResult<Void> test5(@NotBlank(message = "name不能为空")  @RequestParam(required = true)  String name){

        return ApiResult.ok();
    }

    /**
     * 验证 get 请求时，使用@PathVariable 参数校验生效的情况，会被ConstraintViolationException异常拦截
     * 注：对restful 风格的传参，如果为空，无法校验，但可以对参数的范围进行校验
     * @param name
     * @return
     */
    @GetMapping("/test01/{name}")
    public ApiResult<Void> test6(@NotNull(message = "name不能为空")  @Min (4)@PathVariable(value = "name")  Integer name){

        List<String> strings = Arrays.asList("1", "2", "3");
        //存入Map
        Map<String,Object>  map=  new HashMap<String,Object>();
        map.put("key1","value1");
        map.put("key2","value");
        ApiResult.ok(map);
         // 返回 map
        return ApiResult.ok(strings);
    }

    /**
     * 验证 Assert 异常返回
     * @param
     * @return
     */
    @GetMapping("test07")
    public ApiResult<Void> test7(){
        Student stu=null;
       // BeanUtils.copyProperties();
        JSONObject obj = JSONUtil.createObj();
        Assert.notNull(stu, ApiCode.ERROR_AUTH);

        return ApiResult.ok();
    }


    @PostMapping (value = "test08",produces = "application/json;charset=UTF-8")
    public ApiResult<Void> test8(@RequestBody Student su){
        Student stu=null;
        // BeanUtils.copyProperties();

        Assert.notNull(stu, ApiCode.ERROR_AUTH);
        return ApiResult.ok();
    }

    @PostMapping (value = "test09")
    public ApiResult<Void> test9(Map<String,String> map){
        System.out.println("ttttt");


        return ApiResult.ok();
    }

}
